/*
 * @Description: 分货计划页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2020-10-21 17:30:52
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-09 15:27:30
 */

import React, { useCallback, useMemo, useRef, useState } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import {
  Button,
  DataSet,
  MonthPicker,
  notification,
  Select,
  Table,
  TextField,
} from 'choerodon-ui/pro';
import { ButtonColor } from 'choerodon-ui/pro/lib/button/enum';
import { useDataSet, useDataSetEvent } from 'hzero-front/lib/utils/hooks';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import { TableColumnTooltip } from 'choerodon-ui/pro/lib/table/enum';
import intl from 'utils/intl';
import { getAccessToken } from 'hzero-front/lib/utils/utils';
import { getCurrentTenant } from 'utils/utils';
import request from 'utils/request';
import { distributionPlanDS, productMakeDS } from '../../stores/distributionPlanDS';
import { renderSort, useQueryParams, addEnterCallBack } from '../../utils/utilsFun';
import CustomizeTableSearch from '@common/components/CustomizeTableSearch';
import ExcelExport from 'components/ExcelExport';
import commonConfigStore from '@common/config/commonConfig';
import { routerRedux } from 'dva/router';
import querystring from 'querystring';
import { connect } from 'dva';
import formatterCollections from 'utils/intl/formatterCollections';
const O2_OM = process.env.NODE_ENV === 'development' ? '/o2om-c' : commonConfigStore.O2_OM;

notification.config({
  duration: 3,
  placement: 'bottomRight',
});
interface propType {
  [key: string]: any;
}

const ClassPage: React.FC<propType> = ({ dispatch }) => {
  const tableDS = useDataSet(() => new DataSet(distributionPlanDS() as DataSetProps));
  const productMakingDS = useDataSet(() => new DataSet(productMakeDS() as DataSetProps));
  const queryObj = useQueryParams(tableDS);

  const [confirmData, setConfirmData] = useState({});
  const pageRef = useRef(null);

  // 添加按回车查询事件
  addEnterCallBack(tableDS, pageRef);

  useDataSetEvent(tableDS, 'loadFailed', ({ dataSet }) => {
    const queryData = dataSet.queryDataSet.current.toData();
    const { controlModeCode, quotaMonth } = queryData;
    if (!controlModeCode || !quotaMonth) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get(`dji.otc.om.view.reminder.lackOfConditionsQueryFailed`).d('查询条件数集不通过,查询失败！！'),
      });
    }
  });

  useDataSetEvent(tableDS, 'load', ({ dataSet }) => {
    const reqDadta = dataSet.toData();
    if (reqDadta.length > 0) {
      setConfirmData({
        quotaMonth: reqDadta[0].quotaMonth,
        version: reqDadta[0].version,
        controlModeCode: reqDadta[0].controlModeCode,
      });
    } else {
      setConfirmData({});
    }
  });


  const handleBatchExport = useCallback(
    () => {
      dispatch(
        routerRedux.push({
          pathname: `/o2om/distribution/excel-import/O2OM_C.QUOTA_PLAN`,
          search: querystring.stringify({
            action: intl.get(`dji.otc.om.view.reminder.distributionImport`).d('分货列表导入'),
            prefixPath: 'O2OM_C.QUOTA_PLAN',
          }),
        })
      );
    },
    [],
  )

  const Columns = useMemo<any>(
    () => [
      {
        header: intl.get(`dji.otc.om.view.field.serialNumber`).d('序号'),
        width: 50,
        lock: true,
        renderer: ({ record }) => renderSort(record, tableDS),
      },
      { name: 'quotaMonth', align: 'left', tooltip: TableColumnTooltip.always, lock: true },
      { name: 'version', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'controlModeMeaning', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'shortageTypeMeaning', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'regionName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'areaName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'businessGroupMeaning', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'customerName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'retailer', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'productCategory', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'productCode', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'productName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'quantityDemand', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'satisfactionRate', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'quantitySupply', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'useQuantity', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'quantityFirstWeek', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'quantitySecondWeek', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'quantityThirdWeek', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'quantityFourthWeek', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'createdUserName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'creationDate', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'planStatusCode', align: 'left', tooltip: TableColumnTooltip.always },
    ],
    []
  );

  // 删除选择行
  const handleDelete = () => {
    const seletedRecord = tableDS.selected;
    if (seletedRecord.length === 0) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get(`dji.otc.om.view.reminder.selectDeleteData`).d('请勾选删除的数据'),
      });
      return;
    }
    tableDS.delete(seletedRecord);
  };

  const accessToken = getAccessToken();
  const currentTenant = getCurrentTenant();

  const handleExportModel = () => {
    request(
      `/himp/v1/0/template/O2OM_C.QUOTA_PLAN/excel?access_token=${accessToken}&tenantId=${currentTenant.tenantId}`,
      {
        method: 'GET',
        responseType: 'blob',
      }
    ).then(res => {
      if (res) {
        const bl = new Blob([res]);
        const fileName = intl
          .get('dji.otc.om.view.reminder.distributionImportMode')
          .d('分货计划列表导入模版');
        const link = document.createElement('a');
        document.body.appendChild(link);
        link.style.display = 'none';
        link.href = window.URL.createObjectURL(bl);
        link.download = `${fileName}.xlsx`;
        link.click();
        document.body.removeChild(link);
      }
    });
  };

  const productComfirm = () => {
    const queryData = (tableDS.queryDataSet as any).current?.toData();
    const { controlModeCode, quotaMonth } = queryData;
    if (!controlModeCode || !quotaMonth) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get(`dji.otc.om.view.reminder.unableToConfirmProductionAndMarketing`).d('查询条件数集不通过,查询失败,无法产销确认！！'),
      });
      return;
    }
    if (Object.keys(confirmData).length === 0) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get(`dji.otc.om.view.reminder.noDataToConfirm`).d('列表无数据可以产销确认'),
      });
      return;
    }
    productMakingDS.loadData([confirmData]);
    productMakingDS.submit().then(() => {
      tableDS.query();
    });
  };

  return (
    <div ref={pageRef}>
      <PageHeaderWrapper
        title={intl.get('dji.otc.om.view.menu.distributionPlan').d('分货计划')}
        header={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <ExcelExport
              defaultSelectAll
              queryParams={queryObj}
              requestUrl={`${O2_OM}/v1/quota-plans/export`}
              defaultConfig={{
                fileName: intl
                  .get('dji.otc.om.view.reminder.distributionListExport')
                  .d('分货列表导出结果'), // 文件名
                fillerType: 'single-sheet', // 导出类型
              }}
              otherButtonProps={{
                style: { marginRight: '10px' },
              }}
            />
            <Button icon="get_app" key="import" onClick={() => handleBatchExport()}>
              {intl.get(`dji.otc.om.view.button.import`).d('导入')}
            </Button>
            <Button icon="export" key="export" onClick={() => handleExportModel()}>
              {intl.get(`dji.otc.om.view.button.exportMode`).d('导出模板')}
            </Button>
            <Button onClick={() => handleDelete()}>
              {intl.get(`dji.otc.om.view.button.delete`).d('删除')}
            </Button>
            <Button onClick={() => productComfirm()} color={ButtonColor.primary}>
              {intl.get(`dji.otc.om.view.button.marketingConfirmation`).d('产销确认')}
            </Button>
          </div>
        }
      >
        <Table
          dataSet={tableDS}
          // autoHeight={{ type: TableAutoHeightType.maxHeight, diff: 80 }}
          border
          columns={Columns}
          queryFieldsLimit={3}
          queryBar={props => (
            <CustomizeTableSearch
              elements={[
                <MonthPicker name="quotaMonth" key="quotaMonth" />,
                <Select name="controlModeCode" key="controlModeCode" searchable />,
                <TextField name="customerName" key="customerName" />,
                <TextField name="productName" key="productName" />,
                <Select name="largeAreaObj" key="largeAreaObj" searchable />,
                <Select name="areaObj" key="areaObj" searchable />,
                <Select name="customerType" key="customerType" searchable />,
                <TextField name="retailer" key="retailer" />,
                <TextField name="productCategory" key="productCategory" />,
                <Select name="businessGroup" key="businessGroup" searchable />,
                <TextField name="version" key="version" />,
              ]}
              // eslint-disable-next-line react/jsx-props-no-spreading
              {...props}
            />
          )}
        />
      </PageHeaderWrapper>
    </div>
  );
};

export default connect()(
  formatterCollections({
    code: 'dji.otc.om',
  })(ClassPage)
);

